package com.inossem.warehousestorage_inossem.activity.in_storage;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.inossem.utils.base.RegexUtils;
import com.inossem.utils.listener.NoDoubleClickListener;
import com.inossem.warehousestorage_inossem.R;
import com.inossem.warehousestorage_inossem.activity.base.BaseActivity;
import com.inossem.warehousestorage_inossem.activity.in_storage.extra.InStorageExtra;
import com.inossem.warehousestorage_inossem.bean.inStorage.InStorageTenderOverviewBean;
import com.inossem.warehousestorage_inossem.dialog.DialogUtils;
import com.inossem.warehousestorage_inossem.utils.ActivityUtils;
import com.inossem.warehousestorage_inossem.utils.InStorageUtils;
import com.zhy.android.percent.support.PercentLinearLayout;

import java.util.List;

public class InStorageTenderMaterielDetailActivity extends BaseActivity {

    private static final String TYPE_EDITTEXT = "0";

    private static final String TYPE_DATEPICKER = "1";

    private static final String TYPE_SELECT = "2";

    private static final String REQUIRED_NO = "0";

    private static final String REQUIRED_YES = "1";

    private TextView title, serialNumber, materielCode, materielDescription, orderNumber, receivedNumber, factory, demandCompany, inventoryAddress, costObject, objectDescription;

    private EditText inStorageNumber;

    private String serialNumberStr, unit;

    private InStorageTenderOverviewBean.DataBean.FreeInStorageListBean materielItem;

    private PercentLinearLayout batchLayout;

    @Override
    protected void onCreateImpl(Bundle savedInstanceState) {
        setContentView(R.layout.activity_in_storage_tender_materiel_detail);
        initView(InStorageTenderMaterielDetailActivity.this);
        initData(InStorageTenderMaterielDetailActivity.this);
    }

    private void initView(Activity activity) {
        title = (TextView) activity.findViewById(R.id.headerTitle);
        serialNumber = (TextView) activity.findViewById(R.id.serialNumber);
        materielCode = (TextView) activity.findViewById(R.id.materielCode);
        materielDescription = (TextView) activity.findViewById(R.id.materielDescription);
        orderNumber = (TextView) activity.findViewById(R.id.orderNumber);
        receivedNumber = (TextView) activity.findViewById(R.id.receivedNumber);
        inStorageNumber = (EditText) activity.findViewById(R.id.inStorageNumber);
        factory = (TextView) activity.findViewById(R.id.factory);
        demandCompany = (TextView) activity.findViewById(R.id.demandCompany);
        inventoryAddress = (TextView) activity.findViewById(R.id.inventoryAddress);
        costObject = (TextView) activity.findViewById(R.id.costObject);
        objectDescription = (TextView) activity.findViewById(R.id.objectDescription);
        batchLayout = (PercentLinearLayout) activity.findViewById(R.id.batchLayout);
    }

    private void initData(BaseActivity activity) {
        title.setText(activity.getResources().getString(R.string.activity_receive_materiel_detail_title));
        ActivityUtils.initBackAndFunction(activity, R.string.activity_receive_receive_item_title_short, new NoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                backAndUpdate();
            }
        });
        getExtra(activity);
        getData(activity);
    }

    private void getExtra(Activity activity) {
        serialNumberStr = activity.getIntent().getStringExtra(InStorageExtra.SERIAL_NUMBER);
    }

    private void getData(BaseActivity context) {
        materielItem = InStorageUtils.getTenderMaterielInformationBySerial(context, serialNumberStr);
        unit = materielItem.getUnit();
        serialNumber.setText(materielItem.getSerial());
        materielCode.setText(materielItem.getMaterielCode());
        materielDescription.setText(materielItem.getMaterielDescription());
        orderNumber.setText(materielItem.getOrderNumber() + unit);
        receivedNumber.setText(materielItem.getReceivedNumber() + unit);
        inStorageNumber.setText(TextUtils.isEmpty(materielItem.getInStorageNumber()) ? "" : (materielItem.getInStorageNumber() + unit));
        factory.setText(materielItem.getFactoryCode() + " - " + materielItem.getFactoryValue());
        demandCompany.setText(materielItem.getDemandCompany());
        inventoryAddress.setText(materielItem.getInventoryAddressCode() + " - " + materielItem.getInventoryAddressValue());
        costObject.setText(materielItem.getCostObject());
        objectDescription.setText(materielItem.getObjectDescription());
        inventoryAddress.setOnClickListener(new NoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                DialogUtils.getTenderInventoryAddressDialog(context, InStorageUtils.getTenderInventoryAddressList(context), new DialogUtils.TenderInventoryAddressListener() {
                    @Override
                    public void onSelect(Dialog dialog, String inventoryAddressValue, String inventoryAddressCode, String factoryValue, String factoryCode) {
                        inventoryAddress.setText(inventoryAddressCode + " - " + inventoryAddressValue);
                        factory.setText(factoryCode + " - " + factoryValue);
                    }
                }).show();
            }
        });
        List<InStorageTenderOverviewBean.DataBean.FreeInStorageListBean.BatchBean> batchList = materielItem.getBatch();
        for (int i = 0; i < batchList.size(); i++) {
            InStorageTenderOverviewBean.DataBean.FreeInStorageListBean.BatchBean batchItem = batchList.get(i);
            String type = batchItem.getType();
            boolean required = REQUIRED_YES.equals(batchItem.getRequired()) ? true : false;
            switch (type) {
                case TYPE_EDITTEXT:
                    InStorageUtils.createEditText(context, batchLayout, batchItem.getName(), required, batchItem.getText(), batchItem.getValue(), i + 1);
                    break;
                case TYPE_DATEPICKER:
                    InStorageUtils.createDatePicker(context, batchLayout, batchItem.getName(), required, batchItem.getText(), batchItem.getValue(), i + 1);
                    break;
                case TYPE_SELECT:
                    InStorageUtils.createTenderSelect(context, batchLayout, batchItem.getName(), required, batchItem.getText(), batchItem.getValue(), batchItem.getSelect(), i + 1);
                    break;
            }
        }
        inStorageNumber.setOnFocusChangeListener((View v, boolean hasFocus) -> {
            if (hasFocus) {
                inStorageNumber.setText("");
            }
        });
    }

    private void updateInfo(Context context) {
        materielItem.setInStorageNumber(inStorageNumber.getText().toString().replace(materielItem.getUnit(), "").trim());
        String[] inventoryAddressArray = inventoryAddress.getText().toString().split(" - ");
        materielItem.setInventoryAddressCode(inventoryAddressArray[0]);
        materielItem.setInventoryAddressValue(inventoryAddressArray[1]);
        String[] factoryArray = factory.getText().toString().split(" - ");
        materielItem.setFactoryCode(factoryArray[0]);
        materielItem.setFactoryValue(factoryArray[1]);
        List<InStorageTenderOverviewBean.DataBean.FreeInStorageListBean.BatchBean> batchList = materielItem.getBatch();
        for (int i = 0; i < batchList.size(); i++) {
            InStorageTenderOverviewBean.DataBean.FreeInStorageListBean.BatchBean batchItem = batchList.get(i);
            String type = batchItem.getType();
            View view = findViewById(i + 1);
            switch (type) {
                case TYPE_EDITTEXT:
                    batchItem.setText(((EditText) view.findViewById(R.id.text)).getText().toString());
                    break;
                case TYPE_DATEPICKER:
                    batchItem.setText(((TextView) view.findViewById(R.id.text)).getText().toString());
                    break;
                case TYPE_SELECT:
                    batchItem.setValue(((TextView) view.findViewById(R.id.value)).getText().toString());
                    batchItem.setText(((TextView) view.findViewById(R.id.text)).getText().toString());
                    break;
            }
        }
        InStorageUtils.updateTenderInStorageItem(context, materielItem);
    }

    private String check(Context context) {
        String inStorageNumberStr = inStorageNumber.getText().toString().replace(materielItem.getUnit(), "").trim();
        if ("".equals(inStorageNumberStr)) {
            return "入库数量不可以为空";
        }

        if (!RegexUtils.checkDecimal(inStorageNumberStr)) {
            return "入库数量非法";
        }

        if (RegexUtils.checkZero(inStorageNumberStr)) {
            return "入库数量必须大于0";
        }

        float maxNumber = Float.parseFloat(materielItem.getOrderNumber()) - Float.parseFloat(materielItem.getReceivedNumber());
        float inStoragetNumberFloat = Float.parseFloat(inStorageNumberStr);
        if (inStoragetNumberFloat > maxNumber) {
            return "入库数量不能大于订单数量减去已收数量";
        }
        List<InStorageTenderOverviewBean.DataBean.FreeInStorageListBean.BatchBean> batchList = materielItem.getBatch();
        for (int i = 0; i < batchList.size(); i++) {
            InStorageTenderOverviewBean.DataBean.FreeInStorageListBean.BatchBean batchItem = batchList.get(i);
            String name = batchItem.getName();
            String type = batchItem.getType();
            String required = batchItem.getRequired();
            if (REQUIRED_YES.equals(required)) {
                View view = findViewById(i + 1);
                if (TYPE_EDITTEXT.equals(type)) {
                    EditText textEditText = (EditText) view.findViewById(R.id.text);
                    if ("".equals(textEditText.getText().toString())) {
                        return name + "为必填项，不可以为空";
                    }
                } else {
                    TextView textTextView = (TextView) view.findViewById(R.id.text);
                    if ("".equals(textTextView.getText().toString())) {
                        return name + "为必填项，不可以为空";
                    }
                }
            }
        }
        return null;
    }

    private void backAndUpdate() {
        String checkResult = check(InStorageTenderMaterielDetailActivity.this);
        if (checkResult == null) {
            updateInfo(InStorageTenderMaterielDetailActivity.this);
            super.onBackPressed();
        } else {
            DialogUtils.getConfirmDialog(InStorageTenderMaterielDetailActivity.this, checkResult + "\n" + "是否强制退出?", new DialogUtils.ConfirmDialogListener() {
                @Override
                public void onConfirm(Dialog dialog) {
                    InStorageTenderMaterielDetailActivity.super.onBackPressed();
                }
            }).show();
        }
    }

    @Override
    public void onBackPressed() {
        backAndUpdate();
    }
}
